import { _decorator, AssetManager, assetManager, Component, director, Label, Material, Node, ProgressBar, SpriteAtlas, sys, Vec3 } from 'cc';
import { LocalConfig } from '../../../bundle/framework/csv/LocalConfig';
import { GGAudio } from '../../../bundle/framework/core/base/GGAudio';

import { WECHAT } from 'cc/env';
import Config from '../../../bundle/common/src/util/Config';
import DataMgr from '../../../bundle/common/src/util/DataMgr';
import SDKManager from '../../../bundle/common/src/manager/SDKManager';
const { ccclass, property } = _decorator;

@ccclass('SplashScene')
export class SplashScene extends Component {

    @property( {type: ProgressBar, displayName: "进度"} )
    progress: ProgressBar = null;

    @property( {type: Label, displayName: "进度标签"} )
    currentPro: Label = null;

    @property( {type: Label, displayName: "加载中"} )
    loadingText: Label = null;

    @property( {type: Node, displayName: "进度图标"} )
    iconRun: Node = null;

    private loadStartTime: number = 0
    private bundleVer: string

    // 进度
    private proIndex = 0
    private nexProIndex = 0
    private timeIndex = 0
    
    // 加载数量
    private loadIndex: number = 0

    // =======================================
    // Component 生命周期
    // =======================================
    protected async start() {
        this.initValues()
        this.initSDKS()

        this.alignProgress( 0 )

        this.loadConfigsBundle()
        this.loadAudioBundle()
        this.loadStartBundle()
        this.loadGameBundle()
    }

    update(dt: any): void {
        if (this.proIndex <= this.nexProIndex) {
            this.progress.progress = this.proIndex / 100.0
            this.currentPro.string = Math.floor(this.proIndex) + "%"
            this.proIndex += 1

            const pos = this.iconRun.position

            this.iconRun.position = new Vec3(-250 + 500 * this.progress.progress, pos.y, pos.z)
        }

        this.timeIndex++
        const dots = Math.floor( this.timeIndex / 30 ) % 4
        if (dots == 0) 
            this.loadingText.string = "加载中"
        else if (dots == 1)
            this.loadingText.string = "加载中."
        else if (dots == 2)
            this.loadingText.string = "加载中.."
        else if (dots == 3)
            this.loadingText.string = "加载中..."
    }

    // ------------------------ 初始化 ------------------------ //
    private initValues() {
        gg.log('StartScene Init Value');

        this.loadStartTime = Date.now();
        this.bundleVer = sys.localStorage.getItem('__bundleVersionConfig__');

        if (WECHAT) {
            wx.getDeviceBenchmarkInfo({
                success (res) {
                    Config.benchmarkLevel = res.benchmarkLevel
                }
            })
        }
    }

    // 初始化数据
    private initSDKS() {
        GGAudio.init()
        SDKManager.initSDK()
    }

    // ------------------------ 内部方法 ------------------------ //

    private alignProgress(value: number) {
        this.nexProIndex = value
        if (this.proIndex < this.nexProIndex) {
            // this.proIndex = this.nexProIndex
            
            this.progress.progress = this.proIndex / 100.0
            this.currentPro.string = Math.floor(this.proIndex) + "%"
        }
    }

    private goIntoStart() {
        this.loadIndex++
        if (this.loadIndex == 2) {
            director.loadScene('start')
        }
    }

    // ------------------------ 加载功能 ------------------------ //
    // 加载表格包
    private loadConfigsBundle() {
        assetManager.loadBundle('tables', { version: this.bundleVer }, (err, bundle) => {
            if (err) { return gg.error(err); }

            LocalConfig.instance.loadConfig(() => {
                Config.levelConfig = LocalConfig.instance.getTable("levelConfig")
                Config.wordsConfig = LocalConfig.instance.getTable("wordsConfig")
                Config.ruleConfig = LocalConfig.instance.getTable("ruleConfig")
                Config.guanzhiConfig = LocalConfig.instance.getTable("guanzhiConfig")
                Config.moneyConfig = LocalConfig.instance.getTable("moneyConfig")
            }, "tables");
        });
    }

    // 加载音效包
    private loadAudioBundle() {
        assetManager.loadBundle('audio', { version: this.bundleVer }, (err, bundle) => {
            if (err) { return gg.error(err); }
        });
    }

    // 加载启动包
    private loadStartBundle() {
        const self = this
        assetManager.loadBundle('start', { version: this.bundleVer }, (err, bundle) => {
            if (err) { return gg.error(err); }
                                    
            bundle.loadScene('start', (err, scene) => {
                if (err) { return gg.error(err); }
                console.log("加载 start 花费了时间: ", ((Date.now() - this.loadStartTime) / 1000));
                                
                self.goIntoStart()
            })
        });
    }

    // 加载游戏包
    private loadGameBundle() {
        const self = this
        assetManager.loadBundle('game', { version: this.bundleVer }, (err, bundle) => {
            if (err) { return gg.error(err); }
            
            bundle.loadScene('game', (err, scene) => {
                if (err) { return gg.error(err); }

                console.log("加载 game 花费了时间: ", ((Date.now() - this.loadStartTime) / 1000));
                self.goIntoStart()
            });
        });
    }
}
